package com.songqintuan.mall.controller;

import javax.faces.application.Application;



import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import com.songqintuan.common.util.SpringFacesUtil; 
import com.songqintuan.mall.constant.MallConstants;


 public class LoggedInCheck implements PhaseListener {

 /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
public PhaseId getPhaseId() {
	 return PhaseId.RESTORE_VIEW;
 }

 public void beforePhase(PhaseEvent event) {
	 FacesContext fc = SpringFacesUtil.getFacesContext();
	 Application application = fc.getApplication();   
	 ViewHandler viewHandler = application.getViewHandler();
	 if (null != fc.getViewRoot() && null == fc.getViewRoot().getViewId()) {
		 viewHandler.restoreView(fc,fc.getViewRoot().getViewId());
	 }
 }

 public void afterPhase(PhaseEvent event) {
	 FacesContext fc = SpringFacesUtil.getFacesContext();
	
	
	 // Check to see if they are on the login page.
	 boolean needCheckCustomerPage = false;
	 if (null != fc.getViewRoot() && null != fc.getViewRoot().getViewId()) {
		 needCheckCustomerPage = fc.getViewRoot().getViewId().indexOf("/member/") > -1 ? true : false;
	 }
	 if (needCheckCustomerPage && !loggedIn()) {
		 NavigationHandler nh = fc.getApplication().getNavigationHandler();
		 nh.handleNavigation(fc, null, MallConstants.GO_TO_LOGIN + "?faces-redirect=true");
	 }
	 Application application = fc.getApplication();   
	 ViewHandler viewHandler = application.getViewHandler();
	 if (null != fc.getViewRoot() && null == fc.getViewRoot().getViewId()) {
		 viewHandler.restoreView(fc, fc.getViewRoot().getViewId());
	 }
 }
 //验证是否已经登陆
 private boolean loggedIn() {
	 return LoginController.loggedIn();
 }
 } 
